<template>
  <div class="p-4">
    <el-card class="mb-4">
      <template #header>
        <div class="flex justify-between items-center">
          <h3 class="font-semibold text-lg">用户管理</h3>
          <el-button type="primary" @click="handleAddUser">添加用户</el-button>
        </div>
      </template>
      <el-table
        :data="userList"
        stripe
        border
        fit
        highlight-current-row
        @row-dblclick="handleEditUser"
      >
        <el-table-column prop="userNo" label="学号/工号" width="180"></el-table-column>
        <el-table-column label="姓名" width="120">
          <template #default="scope">
            <!-- 将姓名改为可点击链接 -->
            <span 
              class="text-primary cursor-pointer hover:underline"
              @click="goToUserProducts(scope.row)"
            >
              {{ scope.row.name }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="80"></el-table-column>
        <el-table-column prop="college" label="学院" width="180"></el-table-column>
        <el-table-column prop="contact" label="联系方式" width="150"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="200"></el-table-column>
        <el-table-column prop="registerTime" label="注册时间" width="200"></el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEditUser(scope.row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="handleDeleteUser(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="mt-4 flex justify-center">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog v-model="dialogVisible" title="用户信息">
      <template #default>
        <el-form
          ref="userFormRef"
          :model="formData"
          :rules="rules"
          label-width="120px"
          class="form-container"
        >
          <el-form-item label="学号/工号" prop="userNo">
            <el-input v-model="formData.userNo" :disabled="isEditMode"></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="formData.name"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="formData.gender">
              <el-radio :label="'男'">男</el-radio>
              <el-radio :label="'女'">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="学院" prop="college">
            <el-input v-model="formData.college"></el-input>
          </el-form-item>
          <el-form-item label="联系方式" prop="contact">
            <el-input v-model="formData.contact"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="formData.email"></el-input>
          </el-form-item>
          <el-form-item label="注册时间" prop="registerTime">
            <el-date-picker
              v-model="formData.registerTime"
              type="datetime"
              placeholder="选择日期时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'  // 导入路由
import { ElMessage, ElMessageBox } from 'element-plus'

// 路由实例
const router = useRouter()

// 模拟数据
const mockUsers = [
  { userNo: '2023001', name: '张三', gender: '男', college: '计算机科学与技术学院', contact: '13800138001', email: 'zhangsan@example.com', registerTime: '2023-09-01 08:30:00' },
  { userNo: '2023002', name: '李四', gender: '男', college: '电子信息工程学院', contact: '13900139002', email: 'lisi@example.com', registerTime: '2023-09-01 09:15:00' },
  { userNo: '2023003', name: '王五', gender: '男', college: '机械工程学院', contact: '13700137003', email: 'wangwu@example.com', registerTime: '2023-09-01 10:00:00' },
  { userNo: '2023004', name: '赵六', gender: '女', college: '自动化学院', contact: '13600136004', email: 'zhaoliu@example.com', registerTime: '2023-09-01 11:45:00' },
  { userNo: '2023005', name: '钱七', gender: '女', college: '材料科学与工程学院', contact: '13500135005', email: 'qianqi@example.com', registerTime: '2023-09-02 08:00:00' },
  { userNo: '2023006', name: '孙八', gender: '男', college: '能源与动力工程学院', contact: '13400134006', email: 'sunba@example.com', registerTime: '2023-09-02 09:30:00' },
  { userNo: '2023007', name: '周九', gender: '男', college: '电气工程学院', contact: '13300133007', email: 'zhoujiu@example.com', registerTime: '2023-09-02 10:45:00' },
  { userNo: '2023008', name: '吴十', gender: '女', college: '建筑与土木工程学院', contact: '13200132008', email: 'wushi@example.com', registerTime: '2023-09-02 14:00:00' },
  { userNo: '2023009', name: '郑十一', gender: '女', college: '化学与化工学院', contact: '13100131009', email: 'zhengshiyi@example.com', registerTime: '2023-09-03 08:15:00' },
  { userNo: '2023010', name: '王十二', gender: '男', college: '环境科学与工程学院', contact: '13000130010', email: 'wangshier@example.com', registerTime: '2023-09-03 09:45:00' },
  { userNo: '2023011', name: '陈十三', gender: '男', college: '数学与统计学院', contact: '13800138011', email: 'chenshisan@example.com', registerTime: '2023-09-03 11:30:00' },
  { userNo: '2023012', name: '李十四', gender: '女', college: '物理学院', contact: '13900139012', email: 'lishisi@example.com', registerTime: '2023-09-04 08:45:00' },
  { userNo: '2023013', name: '张十五', gender: '男', college: '化学学院', contact: '13700137013', email: 'zhangshiwu@example.com', registerTime: '2023-09-04 10:30:00' },
  { userNo: '2023014', name: '刘十六', gender: '女', college: '生命科学学院', contact: '13600136014', email: 'liushiliu@example.com', registerTime: '2023-09-04 14:15:00' },
  { userNo: '2023015', name: '黄十七', gender: '男', college: '管理学院', contact: '13500135015', email: 'huangshiqi@example.com', registerTime: '2023-09-05 09:00:00' },
  { userNo: '2023016', name: '周十八', gender: '女', college: '经济学院', contact: '13400134016', email: 'zhoushiba@example.com', registerTime: '2023-09-05 10:45:00' },
  { userNo: '2023017', name: '吴十九', gender: '男', college: '文学院', contact: '13300133017', email: 'wushijiu@example.com', registerTime: '2023-09-05 14:30:00' },
  { userNo: '2023018', name: '郑二十', gender: '女', college: '外国语学院', contact: '13200132018', email: 'zhengershi@example.com', registerTime: '2023-09-06 08:30:00' }
]

// 状态管理
const userList = ref([])
const dialogVisible = ref(false)
const isEditMode = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const localUsers = ref([...mockUsers])

// 表单数据
const formData = reactive({
  userNo: '',
  name: '',
  gender: '男',
  college: '',
  contact: '',
  email: '',
  registerTime: '',
})

// 表单验证规则
const rules = reactive({
  userNo: [
    { required: true, message: '请输入学号/工号', trigger: 'blur' },
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' },
  ],
  college: [
    { required: true, message: '请输入学院', trigger: 'blur' },
  ],
  contact: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
  ],
  registerTime: [
    { required: true, message: '请选择注册时间', trigger: 'change' },
  ],
})

// 表单引用
const userFormRef = ref(null)

// 跳转到用户发布的商品页面
const goToUserProducts = (user) => {
  router.push({
    name: '.\ViewItems',  // 假设用户商品页面的路由名称是 'user-products'
    params: {
      userId: user.userNo,  // 传递用户学号/工号作为用户ID
      userName: user.name   // 传递用户姓名
    }
  })
}

// 获取用户列表
const fetchUserList = () => {
  // 模拟分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  userList.value = localUsers.value.slice(start, end)
  total.value = localUsers.value.length
}

// 添加用户
const handleAddUser = () => {
  isEditMode.value = false
  // 重置表单
  Object.keys(formData).forEach(key => {
    formData[key] = key === 'gender' ? '男' : ''
  })
  dialogVisible.value = true
  nextTick(() => {
    userFormRef.value?.resetFields()
  })
}

// 编辑用户
const handleEditUser = (row) => {
  isEditMode.value = true
  // 复制数据到表单
  Object.keys(formData).forEach(key => {
    formData[key] = row[key]
  })
  dialogVisible.value = true
}

// 删除用户
const handleDeleteUser = (row) => {
  ElMessageBox.confirm(
    `确定要删除用户 ${row.name} 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // 从本地数据中删除
      const index = localUsers.value.findIndex(item => item.userNo === row.userNo)
      if (index !== -1) {
        localUsers.value.splice(index, 1)
        ElMessage.success('删除成功')
        fetchUserList()
      } else {
        ElMessage.error('用户不存在')
      }
    })
    .catch(() => {
      // 取消操作，无需处理
    })
}

// 提交表单
const submitForm = () => {
  userFormRef.value?.validate(valid => {
    if (!valid) return false

    if (isEditMode.value) {
      // 更新用户
      const index = localUsers.value.findIndex(item => item.userNo === formData.userNo)
      if (index !== -1) {
        localUsers.value[index] = { ...formData }
        ElMessage.success('更新成功')
      } else {
        ElMessage.error('用户不存在')
      }
    } else {
      // 添加用户
      if (localUsers.value.some(item => item.userNo === formData.userNo)) {
        ElMessage.error('学号/工号已存在')
        return
      }
      localUsers.value.push({ ...formData })
      ElMessage.success('添加成功')
    }
    
    dialogVisible.value = false
    fetchUserList()
  })
}

// 分页相关
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  fetchUserList()
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  fetchUserList()
}

// 生命周期钩子
onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>
/* 自定义样式 */
.form-container {
  padding: 10px 20px;
}
</style>